import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
import logger from 'vuex/dist/logger'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    list:[],
    allPrice:0
  },
  mutations: {
    getList(state,payload){
      state.list = payload
    },
    // 添加数量
    addNum(state,payload){
      state.list[payload.key].sum++
      state.list[payload.key].children.forEach((item) => {
        if(item.id == payload.id){
          item.num++
          state.allPrice += item.price *100
        }
      })
    },
    // 减少数量
    subNum(state,payload){
      if(state.list[payload.key].sum>0){
        state.list[payload.key].sum--
      }
      state.list[payload.key].children.forEach((item) => {
        if(item.id == payload.id){
          if(item.num >0){
            item.num--
            state.allPrice -= item.price *100
          }
        }
      })
    },
  },
  actions: {
    getList(){
      axios.get('/api/list').then(res => {
        this.commit('getList',res.data)
      })
    }
  },
  modules: {
  },
  plugins:[logger()]
})
